<template>
  <div id="FloorManage" class="page-wrapper">
    <div class="selector-wrapper main-card wrapper">
      <div class="main-card">
        <GroupSelector :selectorData="selectorData" />
      </div>
      <el-button type="primary" @click="handleSubmitClick">获取数据</el-button>
    </div>

    <h1 class="main-title">统计</h1>

    <div class="wrapper main-card">
      <div>
        <el-table :data="spendrecordtotal" style="width: 100%">
          <el-table-column prop="buildingName" label="楼栋"></el-table-column>

          <el-table-column prop="rechargeMoney" label="充值金额">
            <template slot-scope="scope">
              {{ formatTwoDecimals(scope.row.rechargeMoney) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="rechargeNumber"
            label="充值电数(度)"
          ></el-table-column>
          <!-- <el-table-column prop="data" label="用表日期"></el-table-column> -->
        </el-table>
      </div>
    </div>

    <h1 class="main-title">明细</h1>
    <div class="wrapper main-card">
      <div>
        <el-table :data="pageData" style="width: 100%">
          <el-table-column prop="SS_MC" label="房间号"> </el-table-column>
          <el-table-column prop="meterNumber" label="电表编号">
          </el-table-column>
          <el-table-column prop="money" label="充值金额"></el-table-column>
          <el-table-column
            prop="payNumber"
            label="充值电数(度)"
          ></el-table-column>

          <el-table-column property="updatedAt" label="用表日期">
            <template slot-scope="scope">
              {{ formatDate(scope.row.updatedAt) }}
            </template></el-table-column
          >
        </el-table>
      </div>
    </div>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { meterrechargereport } from '@/api/rechargestatistics'
import { getmeterread } from '@/api/meterread'
import GroupSelector from './components/GroupSelector'

export default {
  name: 'RoomInfo',
  components: {
    GroupSelector
  },
  data() {
    return {
      formData: {},
      tableData: [{}],
      currentItem: {},
      currentPage: 1,
      pageData: [],
      total: '',
      pageSize: 10,
      dialogVisible: false,
      selectorData: {
        buildingId: null,
        floorId: null,
        roomId: null,
        dateRange: null,
        value1: null
      },
      modifydata: {},
      currentRow: null,
      spendrecordtotal: {},
      strTime: '',
      endTime: ''
    }
  },
  mounted() {
    // this.meterrechargereport()
    // meterrechargereport().then(res => {
    //   this.total = res.data.spendrecord.length
    //   if (res.success == true) {
    //     this.tableData = res.data.spendrecord
    //     this.pageData = this.queryByPage()
    //   }
    // })
  },
  methods: {
    queryByPage() {
      // 起始位置 = (当前页 - 1) x 每页的大小
      const start = (this.currentPage - 1) * this.pageSize
      // 结束位置 = 当前页 x 每页的大小
      const end = this.currentPage * this.pageSize

      return this.tableData.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val

      this.pageData = this.queryByPage()
    },
    handleCurrentChange(val) {
      this.currentPage = val

      this.pageData = this.queryByPage()
    },
    formatTwoDecimals(value) {
      return parseFloat(value).toFixed(3)
    },
    formatDate(isoString) {
      const date = new Date(isoString)
      const options = {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }
      return date.toLocaleString('zh-CN', options)
    },
    // 获取服务器数据
    meterrechargereport() {
      meterrechargereport()
        .then(res => {
          console.log(res.data)
          console.log('页码', res.data.meterrecharge.length)
          this.tableData = res.data.meterrecharge
          this.spendrecordtotal = res.data.metersubsidietotal

          this.total = res.data.meterrecharge.length // 设置总数据量
          this.pageData = this.queryByPage() // 初始化分页数据
        })
        .catch(err => {
          console.log(err)
        })
    },
    handleSwitchChange(row) {
      console.log(row)
      upmeter(row).then(res => {
        console.log(res.data.result.state)
        if (res.data.result.state === '1') {
          this.$message.success('开关已打开')
        } else {
          this.$message.warning('开关已关闭')
        }
      })
    },
    //搜索按钮
    handleSubmitClick() {
      let strTime // 声明变量
      let endTime // 声明变量

      // 检查是否选择了日期范围
      if (this.selectorData.value1 && this.selectorData.value1.length === 2) {
        // 用户选择了日期范围，转换为 ISO 8601 格式
        strTime = this.convertDateTime(this.selectorData.value1[0])
        endTime = this.convertDateTime(this.selectorData.value1[1])
      } else {
        // 用户没有选择日期范围，使用默认值
        let defaultDate = new Date()
        defaultDate.setUTCFullYear(2024, 4, 24) // 设置为指定日期
        defaultDate.setUTCHours(0, 0, 0, 0) // 将时间设置为00:00:00.000
        strTime = defaultDate.toISOString()
        endTime = new Date(
          defaultDate.getTime() + 24 * 60 * 60 * 1000
        ).toISOString() // 默认时间为24小时后
      }



      let data = {
        startTime: strTime,
        endTime: endTime,
        buildingId: this.selectorData.buildingId,
        floorId: this.selectorData.floorId,
        roomId: this.selectorData.roomId
      }
      // console.log('搜索', data)

      meterrechargereport(data)
        .then(res => {
          console.log(111,res)
          this.total = res.data.meterrecharge.length
          if (res.success == true) {
            this.tableData = res.data.meterrecharge
            this.spendrecordtotal = res.data.metersubsidietotal
            this.pageData = this.queryByPage()

          } else {
            this.$message.error('获取数据失败')
          }
        })
        .catch(error => {
          console.error(error)
          this.$message.error('请求错误')
        })
    },
    convertDateTime(inputString) {
      // 解析输入的日期时间字符串
      const date = new Date(inputString)

      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        throw new Error('Invalid date')
      }

      // 将日期转换为 ISO 8601 格式
      const isoString = date.toISOString()

      // 返回 ISO 字符串
      return isoString
    },
    modify(row) {
      console.log(row)
      this.modifydata = row
      this.dialogVisible = true
    },
    handleSubmit() {
      upmeter(this.modifydata).then(res => {
        console.log(111,res)
        if (res.success == true) {
          this.$message.success('修改成功')
          this.dialogVisible = false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  margin: 40px 0;
}

.selector-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* 垂直居中 */
}

.list-wrapper {
  margin-top: 40px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  /* Adjust margin as needed */
}
</style>
